# this is a namespace package
try:
    import pkg_resources
    pkg_resources.declare_namespace(__name__)
except ImportError:
    import pkgutil
    __path__ = pkgutil.extend_path(__path__, __name__)


__all__ = ['create_app', 'db', 'celery']

import json

from flask import Flask

from .config import config
from extensions import db, celery, rest_api, log, stock_redis, flaskz_setting_mgr
from .modules.tasktest import *
from .modules.stock_update import *
from .models import Setting
from .tasks import *
from extensions.celery_redis_sentinel import register


def create_app(cfg_name, cfg_path=None, **kwargs):

    app = Flask(__name__)

    config[cfg_name].init_app(app, cfg_path)
    app.config.from_object(config[cfg_name])

    configure_extensions(app, cfg_name, **kwargs)
    configure_celery_events(app)
    app.logger.info('\n\n%r' % app.url_map)

    clear_before_run(app)
    configure_stock_settings(app)

    return app


def configure_stock_settings(app):

    with app.app_context():
        cfgs = {}
        settings = Setting.query.filter(Setting.status == 1).all()
        for setting in settings:
            if setting.cfg_type == 'string':
                cfgs[setting.cfg_key] = setting.cfg_value
            elif setting.cfg_type == 'integer':
                cfgs[setting.cfg_key] = int(setting.cfg_value)
            else:
                cfgs[setting.cfg_key] = json.loads(setting.cfg_value)

        app.logger.debug("SETTING FROM DB...")
        app.logger.debug(cfgs)

        flaskz_setting_mgr.init_app(app, cfgs=cfgs)


def clear_before_run(app):
    pass


def configure_celery_events(app):
    pass


def configure_extensions(app, cfg_name, **kwargs):

    db.init_app(app)
    app.extensions['db'] = db

    rest_api.init_app(app)
    add_resource_from_path('stock.modules')

    log.init_app(app)

    register()

    celery.init_app(app)
    celery.flask_app_factory = create_app
    celery.flask_app_args = [cfg_name]
    celery.flask_app_kwargs = kwargs
    app.extensions['celery'] = celery

    stock_redis.init_app(app)


def add_resource_from_path(package_name):
    pass
